package com.hsnn.medstgmini.pro.project.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.pro.project.dao.BidProjhospitalDao;
import com.hsnn.medstgmini.pro.project.model.BidProjhospital;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 医疗机构库
 * @author 
 */
@Repository
public class BidProjhospitalDaoImpl implements BidProjhospitalDao {

	private static final Logger log = Logger
			.getLogger(BidProjhospitalDaoImpl.class);
	@Resource(name = "sessionFactory") 
	private SessionFactory sessionFactory;
	@Autowired 
	private HibernateSqlUtil dao;

	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * 
	 * @category 获取医疗机构信息，排除已在项目中的
	 * @author 邱磊
	 * @date 2015年6月11日 上午11:52:57
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pagination getHospList(Pagination page) {
		StringBuffer hql = new StringBuffer("from HospInfo a where 1=1");

		if (null != page.getConditions() && page.getConditions().size() > 0) {
			if (null != page.getConditions().get("projId")
					&& !"".equals(page.getConditions().get("porjId"))) {
				hql.append(" and exists( select b.projHospId from BidProjhospital b").append(" where a.hospId=b.hospId");
				hql.append(" and b.projId='").append(page.getConditions().get("projId")).append("')");
			}
			if (null != page.getConditions().get("hospName")
					&& !"".equals(page.getConditions().get("hospName"))) {
				hql.append(" and a.hospName like :hospName");
			}
			if (null != page.getConditions().get("hospClassify")
					&& !"".equals(page.getConditions().get("hospClassify"))) {
				hql.append(" and a.hospClassify=:hospClassify");
			}
			if (null != page.getConditions().get("hospCode")
					&& !"".equals(page.getConditions().get("hospCode"))) {
				hql.append(" and a.hospCode=:hospCode");
			}
			if (null != page.getConditions().get("areaId")
					&& !"".equals(page.getConditions().get("areaId"))) {
				hql.append(" and a.area.areaid=:areaId");
			}
			if (null != page.getConditions().get("fahterId")
					&& !"".equals(page.getConditions().get("fahterId"))) {
				hql.append("and a.area.father.areaid=:fahterId");
			}
			if (null != page.getConditions().get("hospSpelCode")
					&& !"".equals(page.getConditions().get("hospSpelCode"))) {
				hql.append(" and a.hospSpelCode like :hospSpelCode");
			}
			if (null != page.getConditions().get("status")
					&& !"".equals(page.getConditions().get("status"))) {
				hql.append(" and a.status = :status");
			}

		}
//		hql.append(" and a.status=1");
		Query query = getSession().createQuery("select count(*) " + hql.toString());
		if (null != page.getConditions() && page.getConditions().size() > 0) {
			// if (null != page.getConditions().get("projId") &&
			// !"".equals(page.getConditions().get("porjId"))){
			// query.setString("projId", page.getConditions().get("porjId"));
			// }
			if (null != page.getConditions().get("hospName")
					&& !"".equals(page.getConditions().get("hospName"))) {
				query.setString("hospName",
						"%" + page.getConditions().get("hospName") + "%");
			}
			if (null != page.getConditions().get("hospClassify")
					&& !"".equals(page.getConditions().get("hospClassify"))) {
				query.setString("hospClassify",
						page.getConditions().get("hospClassify"));
			}
			if (null != page.getConditions().get("hospCode")
					&& !"".equals(page.getConditions().get("hospCode"))) {
				query.setString("hospCode", page.getConditions()
						.get("hospCode"));
			}
			if (null != page.getConditions().get("areaId")
					&& !"".equals(page.getConditions().get("areaId"))) {
				query.setString("areaId", page.getConditions().get("areaId"));
			}
			if (null != page.getConditions().get("fahterId")
					&& !"".equals(page.getConditions().get("fahterId"))) {
				query.setString("fahterId", page.getConditions().get("fahterId"));
			}
			if (null != page.getConditions().get("hospSpelCode")
					&& !"".equals(page.getConditions().get("hospSpelCode"))) {
				query.setString("hospSpelCode",
						"%" + page.getConditions().get("hospSpelCode") + "%");
			}
			if (null != page.getConditions().get("status")
					&& !"".equals(page.getConditions().get("status"))) {
				query.setString("status", page.getConditions().get("status"));
			}
		}
		Long records = (Long) query.uniqueResult();
		page.setRecords(records);
		hql.append(" order by a.hospCode");
		query = getSession().createQuery(hql.toString());
		if (null != page.getConditions() && page.getConditions().size() > 0) {
			// if (null != page.getConditions().get("projId") &&
			// !"".equals(page.getConditions().get("porjId"))){
			// query.setString("projId", page.getConditions().get("porjId"));
			// }
			if (null != page.getConditions().get("hospName")
					&& !"".equals(page.getConditions().get("hospName"))) {
				query.setString("hospName",
						"%" + page.getConditions().get("hospName") + "%");
			}
			if (null != page.getConditions().get("hospClassify")
					&& !"".equals(page.getConditions().get("hospClassify"))) {
				query.setString("hospClassify",
						page.getConditions().get("hospClassify"));
			}
			if (null != page.getConditions().get("hospCode")
					&& !"".equals(page.getConditions().get("hospCode"))) {
				query.setString("hospCode", page.getConditions()
						.get("hospCode"));
			}
			if (null != page.getConditions().get("areaId")
					&& !"".equals(page.getConditions().get("areaId"))) {
				query.setString("areaId", page.getConditions().get("areaId"));
			}
			if (null != page.getConditions().get("fahterId")
					&& !"".equals(page.getConditions().get("fahterId"))) {
				query.setString("fahterId", page.getConditions().get("fahterId"));
			}
			if (null != page.getConditions().get("hospSpelCode")
					&& !"".equals(page.getConditions().get("hospSpelCode"))) {
				query.setString("hospSpelCode",
						"%" + page.getConditions().get("hospSpelCode") + "%");
			}
			if (null != page.getConditions().get("status")
					&& !"".equals(page.getConditions().get("status"))) {
				query.setString("status", page.getConditions().get("status"));
			}
		}
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		List<HospInfo> list = query.list();
		if (list != null && !list.isEmpty()) {
			List<Object> newList = new LinkedList<Object>();
			for (Object obj : list) {
				if (obj != null) {
					newList.add(obj);
				}
			}
			page.setRows(newList);
		}
		return page;
	}
	
	public String addHost(String projId, String hospCode) {
		BidProjhospital data = new BidProjhospital();
		data.setHospCode(hospCode);
		data.setProjHospId(UUID.randomUUID().toString());
		data.setProjId(projId);
		data.setStatus(Short.valueOf("1"));
		data.setUpdDatetime(new Date());
		data.setUpdUser("1");
		try {
			getSession().save(data);
			getSession().flush();
			return "success";
		} catch (Exception e) {
			return "failed";
		}

	}
	public void batchAddHosp(List<HospInfo> list) {
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HospInfo hinfo = list.get(i);
				BidProjhospital data = new BidProjhospital();
				data.setHospCode(hinfo.getHospCode());
				data.setProjHospId(UUID.randomUUID().toString());
				data.setProjId(hinfo.getHospName());
				data.setStatus(Short.valueOf("1"));
				data.setUpdDatetime(new Date());
				data.setUpdUser(null);
				getSession().save(data);
				getSession().flush();
			}

		}
	}
	
	
	
	/**
	 * @category 根据id查询医疗机构信息
	 * @param id
	 * @return
	 */
	public HospInfo getHospInfoById(String id) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(HospInfo.class);
		criteria.add(Restrictions.eq("hospId", id));
		return (HospInfo) criteria.uniqueResult();
	}
	
	/**
	 * @category 启用|停用
	 * @param hospInfo
	 */
	public void changeStatus(HospInfo hospInfo) {
		if (hospInfo != null) {
			HospInfo hi = getHospInfoById(hospInfo.getHospId());
			if (hi != null) {
				hi.setStatus(hospInfo.getStatus());
				hi.setUpdUser(hospInfo.getUpdUser());
				hi.setUpdDateTime(new Date());
				dao.update(hi);
			}
		}
	}

	/**
	 * @category 批量(启用|停用)
	 * @param list
	 */
	public void batchChangeStatus(List<HospInfo> list) {
		if (list != null && list.size() > 0) {
			for (HospInfo hospInfo : list) {
				changeStatus(hospInfo);
			}
		}
	}

	/**
	 * @category  获取有效的医疗机构信息
	 * @author 韩守松
	 * @date   2015年6月30日
	 * @param  @param page
	 * @param  @param bidProjhospital
	 * @param  @return
	 */
	@SuppressWarnings("unchecked")
	public List<BidProjhospital> getBidProjhospitalList(Pagination page,BidProjhospital bidProjhospital) {
		try {
			Date date = new Date();
			SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String strDate = sdFormat.format(date);//当前时间字符串
			//String hospName = bidProjhospital.getHospInfo().getHospName();//医疗机构名称
			Timestamp timeDate = Timestamp.valueOf(strDate);
			StringBuffer hql = new StringBuffer();
			StringBuffer hqlCount = new StringBuffer();
			String projId = bidProjhospital.getProjId();
			hql.append("from BidProjhospital bp where 1=1 ");
			hqlCount.append("select count(*) from BidProjhospital bp where 1=1 ");
			if (StringUtils.isNotEmpty(projId)) {
				hql.append(" and bp.projId = :projId ");
				hqlCount.append(" and bp.projId = :projId ");
			}
			/*if(StringUtils.isNotEmpty(hospName)){
				hql.append(" and (bp.stdCompinfo.hospName like :hospName or bp.stdCompinfo.hospName.compSpelCode like :hospName)");
				hqlCount.append(" and (bp.stdCompinfo.hospName like :hospName or bp.stdCompinfo.hospName.compSpelCode like :hospName)");
			}*/
			hql.append(" and bp.status = 1 ");
			hql.append(" and bp.bidProject.status = 1 ");
			hql.append(" and bp.stdCompinfo.status = 1 ");
			hql.append("  and ( :timeDate between bp.bidProject.starttime and bp.bidProject.endtime ) ");
			hqlCount.append(" and bp.status = 1 ");
			hqlCount.append(" and bp.bidProject.status = 1 ");
			hqlCount.append(" and bp.stdCompinfo.status = 1 ");
			hqlCount.append("  and ( :timeDate between bp.bidProject.starttime and bp.bidProject.endtime ) ");
			Query query = this.getSession().createQuery(hql.toString());
			Query queryCount = this.getSession().createQuery(hqlCount.toString());
			if (StringUtils.isNotEmpty(projId)) {
				query.setParameter("projId", projId);
				queryCount.setParameter("projId", projId);
			}
			/*if(StringUtils.isNotEmpty(hospName)){
				query.setParameter("hospName", "%"+hospName+"%");
				queryCount.setParameter("hospName", "%"+hospName+"%");
			}*/
			query.setParameter("timeDate", timeDate);
			queryCount.setParameter("timeDate", timeDate);
			//bidProjhospital.setCount(Long.valueOf(queryCount.list().get(0)+""));
			query.setFirstResult((page.getPage()-1)*page.getMaxResults());
			query.setMaxResults(page.getMaxResults());
			return query.list();
		} catch (Exception e) {
			log.info("查询配送企业信息异常-->", e);
			return new ArrayList<BidProjhospital>();
		}
	}

}
